package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.WemediaConstants;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author げっしょく
 * @date 2021/11/22
 */
@Service
@Transactional
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    /**
     * 上传素材(视频文件)
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult uploadIV(MultipartFile multipartFile) {
        //截取文件名的后缀
        String filename = multipartFile.getOriginalFilename();
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        //使用UUID生成一个文件名
        String file = UUID.randomUUID().toString() + "." + filename;
        //上传文件到minio
        String path = null;
        try {
            path = fileStorageService.uploadImgFile("", file, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println(path);
        //将文件保存到素材表
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setCreatedTime(new Date());
        //将文件的类型默认为图片, 不收藏
        Short co = 0;
        wmMaterial.setIsCollection(co);
        wmMaterial.setType(co);
        wmMaterial.setUrl(path);
        wmMaterial.setUserId(WmThreadLocalUtil.getThread().getId());
        this.save(wmMaterial);
        //返回数据
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 分页查询素材
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult listIV(WmMaterialDto dto) {
        if (dto == null) {
            return null;
        }

        Short collection = dto.getIsCollection();
        if (collection == null) {
            collection = 0;
        }
        Integer page = dto.getPage();
        if (page == null || page <= 0) {
            page = 1;
        }
        Integer size = dto.getSize();
        if (size == null || size <= 0) {
            size = 10;
        }

        WmUser w = WmThreadLocalUtil.getThread();
        Integer userId = (Integer) w.getId();
        IPage page1 = new Page<>(page, size);
        LambdaQueryWrapper<WmMaterial> lam = new LambdaQueryWrapper<>();
        lam.eq(WmMaterial::getIsCollection, collection);
        lam.eq(WmMaterial::getUserId, userId);
        lam.orderByDesc(WmMaterial::getCreatedTime);
        page1 = page(page1, lam);
        //List<WmMaterial> listIV = wmMaterialMapper.getListIV1((page - 1) * size, size, userId);

        PageResponseResult pageResponseResult = new PageResponseResult(page, size, Integer.valueOf(page1.getTotal() + ""));
        pageResponseResult.setData(page1.getRecords());

        return pageResponseResult;
    }

    /**
     * 删除素材
     *
     * @param id 素材id
     * @return
     */
    @Override
    public ResponseResult deletePicture(Integer id) {
        boolean b = removeById(id);
        if (b) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }
        return ResponseResult.errorResult(501, "文件删除失败");
    }

    /**
     * 取消收藏素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult cancelMaterial(Integer id) {
        //获取当前用户id
        Integer userId = WmThreadLocalUtil.getThread().getId();
        //查询是否有收藏图片
        LambdaUpdateWrapper<WmMaterial> lam = new LambdaUpdateWrapper<>();
        lam.eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, userId).eq(WmMaterial::getIsCollection, 1);
        //取消收藏
        boolean remove = remove(lam);
        if (remove) {
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        } else {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
    }

    /**
     * 收藏素材
     * @param id
     * @return
     */
    @Override
    public ResponseResult collectMaterial(Integer id) {
        //获取当前用户id
        Integer userId = WmThreadLocalUtil.getThread().getId();
        //查询是否有收藏图片
        LambdaUpdateWrapper<WmMaterial> lam = new LambdaUpdateWrapper<>();
        lam.eq(WmMaterial::getId, id).eq(WmMaterial::getUserId, userId).eq(WmMaterial::getIsCollection, 1);
        WmMaterial wmMaterial = getOne(lam);
        //图片查出不为空,则代表该图片被用户保存过了
        if (wmMaterial != null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }else {
            //获取id获取到数据
            WmMaterial material = getById(id);
            //如果根据id查询素材为空则代表素材不存在
            if (material == null) {
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            wmMaterial = new WmMaterial();
            wmMaterial.setUserId(userId);
            wmMaterial.setUrl(material.getUrl());
            wmMaterial.setCreatedTime(new Date());
            wmMaterial.setType(WemediaConstants.WM_NEWS_NONE_IMAGE); //默认设置类型为图片
            wmMaterial.setIsCollection(WemediaConstants.COLLECT_MATERIAL); //设置为收藏
            save(wmMaterial);
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

    }

}
